import CryptoJS from 'crypto-js';

// ESP32-S3 专用加密配置
const BLUFI_KEY_SEED = 'BLUFI_ESP32S3_@2023';

export default {
	// 生成设备密钥
	generateKey(deviceMac) {
		const seed = BLUFI_KEY_SEED + deviceMac.replace(/:/g, '');
		return CryptoJS.MD5(seed).toString();
	},

	// AES-CBC 加密
	aesEncrypt(data, keyHex) {
		const iv = CryptoJS.enc.Hex.parse('00000000000000000000000000000000');
		const encrypted = CryptoJS.AES.encrypt(
			CryptoJS.lib.WordArray.create(data),
			CryptoJS.enc.Hex.parse(keyHex), {
				iv,
				mode: CryptoJS.mode.CBC,
				padding: CryptoJS.pad.Pkcs7
			}
		);
		return encrypted.ciphertext;
	},

	// CRC16 校验（兼容 S3）
	crc16(data) {
		console.log("有数据传入", data);
		let crc = 0x0000;
		const uint8Array = new Uint8Array(data);
		for (const byte of uint8Array) {
			crc ^= byte << 8;
			for (let i = 0; i < 8; i++) {
				crc = crc & 0x8000 ? (crc << 1) ^ 0x1021 : crc << 1;
				crc &= 0xFFFF;
			}
		}
		return crc;
	}
};